package com.zues.daiommiddleware.linstener;

import com.zues.daiommiddleware.config.AliyunVideoProperties;
import com.zues.daiommiddleware.service.SpeechTranscriberService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.connection.Message;
import org.springframework.data.redis.connection.MessageListener;
import org.springframework.stereotype.Component;

@Slf4j
@Component
public class RedisMessageListener implements MessageListener {

    private static AliyunVideoProperties videoProperties;

    private static SpeechTranscriberService speechTranscriberService;

    /**
     * Redis发布-开始识别
     */
    private static final String START_COMMAND = "1";

    /**
     * Redis发布-关闭识别
     */
    private static final String STOP_COMMAND = "2";

    @Autowired
    public void setSpeechTranscriberService(SpeechTranscriberService speechTranscriberService) {
        RedisMessageListener.speechTranscriberService = speechTranscriberService;
    }

    @Autowired
    public void setVideoProperties(AliyunVideoProperties videoProperties) {
        RedisMessageListener.videoProperties = videoProperties;
    }

    @Override
    public void onMessage(Message message, byte[] pattern) {
        handleMessage(new String(message.getChannel()), new String(message.getBody()));
    }

    private void handleMessage(String channel, String body) {
        //开启语音识别
        if (START_COMMAND.equals(body)) {
            start();
        } else if (STOP_COMMAND.equals(body)){
            stop();
        }
    }

    /**
     * 开启语音识别
     */
    public void start() {
        speechTranscriberService = new SpeechTranscriberService(videoProperties.getAppKey(), videoProperties.getAccessToken());
        SpeechListener listener = new SpeechListener();
        //开启识别
        speechTranscriberService.process(listener);
    }

    /**
     * 关闭语音识别
     */
    public void stop() {
        // 关闭服务实例
        speechTranscriberService.shutdown(speechTranscriberService);
    }
}
